package cn.hyq.org.service.impl;

import cn.hyq.basic.service.impl.BaseServiceImpl;
import cn.hyq.basic.util.PageList;
import cn.hyq.org.domain.Department;
import cn.hyq.org.domain.Employee;
import cn.hyq.org.mapper.DepartmentMapper;
import cn.hyq.org.query.DepartmentQuery;
import cn.hyq.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;



    @Override
    public List<Department> queryTree() {
        //查询所有
        List<Department> departments = departmentMapper.loadAll();
        //把全部部门转换成一份map集合，之后就可以使用key找到对应的value
        Map<Long, Department> allDepts = departments.stream().collect(Collectors.toMap(Department::getId, dept -> dept));
        //顶级部门
        ArrayList<Department> firstDepts = new ArrayList<>();
        for (Department tmp : departments) {
            //如果id是空，就是祖辈最上级
            if (tmp.getParent_id()==null){
                //就把它添加到第一层级
                firstDepts.add(tmp);
            }else {
                //只要不是第一层级，我就找到我的上以及并把我放入上一级的Children中
                Department parent = allDepts.get(tmp.getParent_id());
                //判断parent不为空
                if (parent!=null){
                    //添加进去
                    parent.getChildren().add(tmp);
                }
            }
        }
            return firstDepts;
    }


}
